package cn.fenqing.utils;

import cn.fenqing.exception.HttpUtilsException;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fenqing
 */
public class HttpUtils {

    private final static OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder().build();


    public static String get2String(String url, Map<String, String> param, Map<String, String> headers){
        HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(url).newBuilder();
        param.forEach(httpUrlBuilder::addQueryParameter);
        Request.Builder builder = new Request.Builder()
                .url(httpUrlBuilder.build())
                .get();

        headers.forEach(builder::header);

        Call call = OK_HTTP_CLIENT.newCall(builder.build());
        try {
            Response execute = call.execute();
            return execute.body().string();
        } catch (IOException e) {
            throw new HttpUtilsException(e);
        }
    }

    public static String get2String(String url, Map<String, String> param){
        return get2String(url, param, new HashMap<>(8));
    }

    public static String postByData2String(String url, Map<String, String> param, Map<String, String> headers){
        Request.Builder builder = new Request.Builder()
                .url(url)
                .get();

        FormBody.Builder formBuilder = new FormBody.Builder();
        param.forEach(formBuilder::add);
        headers.forEach(builder::header);
        Call call = OK_HTTP_CLIENT.newCall(builder.build());
        try {
            Response execute = call.execute();
            return execute.body().string();
        } catch (IOException e) {
            throw new HttpUtilsException(e);
        }
    }

    public static String postByData2String(String url, Map<String, String> param){
        return postByData2String(url, param, new HashMap<>(2));
    }

    public static void main(String[] args) {
        Map<String, String> maps = new HashMap<>();
        maps.put("page", "1");
        maps.put("limit", "10");
        maps.put("query", "trialProdState%3D%26field%3D%26keyword%3D%26toSupplierCustomerId%3D");

        Map<String, String> headers = new HashMap<>();
        headers.put("x-access-token", "eyJhbGciOiJIUzI1NiJ9.eyJ0ZW5hbnRJZCI6IjEyMjMiLCJ0ZW5hbnRBY2NvdW50IjoieHl5IiwiZXhwIjoxNTkxNzk4NTgwLCJ1c2VySWQiOiIzMzUiLCJhY2NvdW50IjoiYWRtaW4ifQ.uUe5jr1wqyOHTxF48-ZA9xcXAQbjpH_Y2tmxtXRi5BI");

        System.out.println(ObjectUtils.runtime(() -> {
            String string = get2String("http://192.168.100.140:8182/examinecenter/pqc/trialProd/application", maps, headers);
            System.out.println(string);
        }));

    }

}

